package com.christina.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.christina.entity.ChatMessage;
import com.christina.mapper.ChatMessageMapper;
import com.christina.service.ChatMessageService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 聊天消息服务实现类
 * 
 * @author Christina
 */
@Service
public class ChatMessageServiceImpl extends ServiceImpl<ChatMessageMapper, ChatMessage> implements ChatMessageService {
    
    @Override
    public List<ChatMessage> getChatHistoryByUserId(Long userId) {
        QueryWrapper<ChatMessage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                .eq("is_deleted", 0)
                .orderByAsc("create_time");
        return list(queryWrapper);
    }
    
    @Override
    public ChatMessage saveUserMessage(Long userId, String content) {
        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setUserId(userId);
        chatMessage.setContent(content);
        chatMessage.setMessageType("USER");
        save(chatMessage);
        return chatMessage;
    }
    
    @Override
    public ChatMessage saveAssistantMessage(Long userId, String content) {
        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setUserId(userId);
        chatMessage.setContent(content);
        chatMessage.setMessageType("ASSISTANT");
        save(chatMessage);
        return chatMessage;
    }
    
    @Override
    public boolean clearChatHistory(Long userId) {
        QueryWrapper<ChatMessage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        
        List<ChatMessage> chatMessages = list(queryWrapper);
        for (ChatMessage chatMessage : chatMessages) {
            chatMessage.setIsDeleted(1);
        }
        return updateBatchById(chatMessages);
    }
}